<?php

namespace admin\controllers;

use Yii;
use common\helpers\Pager;
use common\helpers\Uploader;
use common\models\ExternalLink;

class ExternalLinkController extends Controller {

    // 设置所属一级导航 不设置表示 就是当前类名
    public $parent = 'information';

    /**
     * @name showing ExternalLink list
     * @return string
     */
    public function actionExternalLinkList()
    {
        if( ! $this->isJson) {
            return $this->render('external-link-list');
        }
        $params = $this->request->post();
        $params['deleted_at'] = 0;
        $query = ExternalLink::filterConditions(ExternalLink::initCondition([['name', 'like'], 'deleted_at'], $params));
        $data['page'] = Pager::page(['page_count' => 20, 'total_count' => $query->count()]);
        $data['infos'] = $query->offset(Pager::offset())->limit(Pager::limit())->asArray()->all();
        return $this->json($data);
    }

    /**
     * @name show ExternalLink information
     * @param id int by get request
     * @return string
     */
    public function actionExternalLinkDetail()
    {
        $externalLink = null;
        $externalLinkId = $this->request->get('id');
        if($externalLinkId && ( ! $externalLink = ExternalLink::canEdit($externalLinkId))) {
            return $this->error('无效的外链（Invalid ExternalLink）', 'external-link/external-link-list');
        }
        return $this->render('external-link-detail', ['data' => $externalLink]);
    }
    /**
     * @name insert ExternalLink
     * @method post
     * @return string html
     */
    public function actionExternalLinkInsert()
    {
        $externalLink = new ExternalLink();
        $externalLink->setPostRequest();
        if ( ! $externalLink->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($externalLink->errors(), 'external-link/external-link-detail');
        }
        if ($externalLink->save()) {
            // 保存成功
            return $this->success('外链（'.$externalLink->name.'）添加成功（Insert Success）', [
                ['title' => '前往外链列表页', 'url' => 'external-link/external-link-list'],
                ['title' => '继续修改外链', 'url' => 'external-link/external-link-detail?id='.$externalLink->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('外链（'.$externalLink->name.'）添加失败，请重试（System Fail）', 'external-link/external-link-detail');
    }
    /***
     * @name 上传图片操作
     * @param $upload array files
     * @return string file path json
     */
    function actionExternalLinkUploader()
    {
        $params = require Yii::getAlias('@common/config/uploader.php');
        // 上传操作
        $uploader = (new Uploader($params['externalLink']))->upload('upload');
        // $this->setStatus($uploader['code'], $uploader['message']);
        return $this->json($uploader);
    }
    /**
     * @name update ExternalLink information
     * @describe use get(id) to find ExternalLink
     * @return string html
     */
    public function actionExternalLinkUpdate()
    {
        /* @var $externalLink ExternalLink */
        // id 为必填项，判断外链存在状态
        $externalLink = ExternalLink::canEdit($this->request->get('id'));
        // 未得到，渲染错误页面
        if( ! $externalLink) {
            return $this->error('无效的外链（Invalid ExternalLink）', 'external-link/external-link-list');
        }
        $oldImage = $externalLink->image;
        $externalLink->setPostRequest();
        if ( ! $externalLink->validate()) {
            // 参数异常，渲染错误页面
            return $this->error($externalLink->errors(), 'external-link/external-link-detail?id='.$externalLink->id);
        }
        if ($externalLink->save()) {
            // 删除原图片
            $externalLink->unlinkImage($oldImage);
            // 保存成功
            return $this->success('外链（'.$externalLink->name.'）更新成功（Update Success）', [
                ['title' => '前往外链列表页', 'url' => 'external-link/external-link-list'],
                ['title' => '继续修改外链', 'url' => 'external-link/external-link-detail?id='.$externalLink->id]
            ]);
        }
        // 参数异常，渲染错误页面
        return $this->error('外链（'.$externalLink->name.'）更新失败，请重试（System Error）', 'external-link/external-link-detail?id='.$externalLink->id);
    }
    /**
     * @name delete ExternalLink
     * @param ids array post request
     * @return string json
     */
    public function actionExternalLinkDelete()
    {
        if( ! (($ids = $this->request->post('id')) || ($ids = $this->request->post('ids')))) {
            return $this->json('Invalid.Param', '请求异常（Invalid Param）');
        }
        else if(ExternalLink::deleteAll(['id' => $ids])) {
            return $this->json(SuccessCode, '外链删除成功（Delete Success）');
        }
        return $this->json('System.Error', '外链删除失败（System Error）');
    }
}
